package org.misalen.web.database.repository.mysql;

import java.util.Date;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.transform.AliasToBeanResultTransformer;
import org.misalen.web.database.dao.mysql.impl.BaseMySqlDaoImpl;
import org.misalen.web.database.model.mysql.pro.ProMapReward;
import org.misalen.web.database.util.PaginationFrom;
import org.springframework.stereotype.Repository;

@Repository
public class ProMapRewardRepository extends BaseMySqlDaoImpl<ProMapReward> {

	public long getValidCountByMap(String mapId) {
		return count("select count(*) from ProMapReward where userId IS NULL and mapId=?0", new Object[] { mapId });
	}

	public ProMapReward getByVideoUser(String userId, String mapId) {
		return get("from ProMapReward where userId=?0 and mapId=?1", new Object[] { userId, mapId });

	}

	public ProMapReward getValidByVideo(String mapId) {
		return get("from ProMapReward where userId IS NULL and mapId=?0", new Object[] { mapId });
	}

	@SuppressWarnings("unchecked")
	public PaginationFrom<ProMapReward> getListByGet(String mapId) {
		PaginationFrom<ProMapReward> paginationFrom = new PaginationFrom<>();
		Session session = this.openSession();
		SQLQuery query = session.createSQLQuery(
				"select A.*,B.userName from ProMapReward A LEFT JOIN ProUser B ON A.userId=B.primaryKey WHERE A.mapId='"
						+ mapId + "' and userId IS NOT NULL GROUP BY A.primaryKey ORDER BY A.money desc");
		query.setResultTransformer(new AliasToBeanResultTransformer(ProMapReward.class));
		List<ProMapReward> list = query.list();
		paginationFrom.setList(list);
		paginationFrom.setTotal((long) list.size());
		paginationFrom.setRows(list.size());
		paginationFrom.setPage(1);
		closeSession(session);
		return paginationFrom;
	}
	
	@SuppressWarnings("unchecked")
	public PaginationFrom<ProMapReward> getMyDetailList(String mapId, PaginationFrom<ProMapReward> paginationFrom) {
		
		Session session = this.openSession();
		SQLQuery query = session.createSQLQuery(
				"select A.*,B.userName from ProMapReward A LEFT JOIN ProUser B ON A.userId=B.primaryKey WHERE A.mapId='"
						+ mapId + "' and userId IS NOT NULL GROUP BY A.primaryKey ORDER BY A.money desc");
		query.setResultTransformer(new AliasToBeanResultTransformer(ProMapReward.class));
		List<ProMapReward> list = query.list();
		paginationFrom.setList(list);
		paginationFrom.setTotal((long) list.size());
		setResultIndex(query, paginationFrom.getPage(), paginationFrom.getRows());
		list = query.list();
		paginationFrom.setList(list);
		closeSession(session);
		return paginationFrom;
	}

	public void saveList(int[] is, int[] is2, String primaryKey) {
		Date date = new Date();
		for (int i = 0; i < is.length; i++) {
			ProMapReward proVideoReward = new ProMapReward();
			proVideoReward.setAddTime(date);
			proVideoReward.setMoney(is[i]);
			proVideoReward.setMoney2(is2[i]);
			proVideoReward.setMapId(primaryKey);
			save(proVideoReward);
		}
	}
}